#include "haptic.h"

vector<Haptic*> Haptic::sActives;

Haptic::Haptic(const string& name, ClassId* classId, int deviceIndex):
Instance(name, classId),
mSdlHaptic(SDL_HapticOpen(deviceIndex))
{
    assert((unsigned int)deviceIndex < sActives.size());

    if (mSdlHaptic) {
        if(sActives[deviceIndex])
            delete sActives[deviceIndex];
        sActives[deviceIndex] = this;
    }
    else
        cerr << "Haptic::Haptic(name, deviceIndex, classId) : Could not open Haptic #" << deviceIndex << endl;
}

Haptic::~Haptic()
{
    if(mSdlHaptic) {
        int deviceIndex = SDL_HapticIndex(mSdlHaptic);
        assert((unsigned int)deviceIndex < sActives.size());
        sActives[deviceIndex] = 0;
        SDL_HapticClose(mSdlHaptic);
        mSdlHaptic = 0;
    }
}


bool Haptic::detectActive()
{
    unsigned int i, numHaptics;

    // Delete already active haptics
    numHaptics = sActives.size();
    for (i=0; i<numHaptics; i++)
        delete sActives[i];

    // Detect & create active haptics
    numHaptics = SDL_NumHaptics();
    sActives.resize(numHaptics);
    for (i=0; i<numHaptics; i++) {
        sActives[i] = 0;
        new Haptic(SDL_HapticName(i), Haptic::sClassId, i);
        if (!sActives[i])
            return false;
    }
    return true;
}

bool Haptic::load(DataStream* ds)
{
    INSTANCE_LOAD(ds);

    return true;
}

bool Haptic::save(DataStream* ds)
{
    INSTANCE_SAVE(ds);

    return true;
}
